<?php

function must_post_request()
{

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['ret' => 1101, 'msg' => 'only accept POST request']);
        exit;
    }
}

// application/x-www-form-urlencoded
// multipart/form-data
function handle_formUrlencoded($name, $func)
{
    $headers = getallheaders();
    $content_type = $headers['Content-Type'];
    if ($content_type == 'application/x-www-form-urlencoded') {
        if (!empty($_POST[$name])) {
            $data = $_POST[$name];
            call_user_func($func, $data);
        } else {
            echo json_encode(['ret' => 1101, 'msg' => 'form-urlencoded need [' . $name . ']']);
        }
        exit;
    }
}

function handle_formdata_file($name, $func)
{
    $headers = getallheaders();
    $content_type = $headers['Content-Type'];
    if (strpos($content_type, 'multipart/form-data') >= 0) {
        if (!empty($_FILES[$name])) {
            $file_data = file_get_contents($_FILES[$name]['tmp_name']);
            call_user_func($func, $file_data);
        } else {
            echo json_encode(['ret' => 1101, 'msg' => 'form-data need [' . $name . '] file']);
        }
        exit;
    }
}
